package com.zhuoya.healthcard.util;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Shader;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class BitmapUtil {
    public static Bitmap base64ToBitmap(final String s) {
        final byte[] decode = Base64Utils.decode(s, 2);
        return BitmapFactory.decodeByteArray(decode, 0, decode.length);
    }

    /* Error */
    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static Bitmap getCircleBitmapByShader(Bitmap paramBitmap, int paramInt1, int paramInt2, int paramInt3) {
        if (paramBitmap == null) {
            return null;
        }
        int i = paramBitmap.getWidth();
        int j = paramBitmap.getHeight();
        float f1 = paramInt1 * 1.0F / i;
        float f2 = paramInt2 * 1.0F / j;
        Matrix localMatrix = new Matrix();
        localMatrix.setScale(f1, f2);
        Bitmap localBitmap = Bitmap.createBitmap(paramInt1, paramInt2, Config.ARGB_8888);
        if (paramInt2 > paramInt1) {
            i = paramInt1 / 2;
        } else {
            i = paramInt2 / 2;
        }
        Canvas localCanvas = new Canvas(localBitmap);
        Paint localPaint = new Paint(1);
        BitmapShader bs = new BitmapShader(paramBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        bs.setLocalMatrix(localMatrix);
        localPaint.setShader(bs);
        localCanvas.drawCircle(paramInt1 / 2, paramInt2 / 2, i - paramInt3, localPaint);
        if (paramInt3 > 0) {
            Paint paint = new Paint(1);
            paint.setColor(Color.parseColor("#CFEEFF"));
            paint.setStyle(Style.STROKE);
            paint.setStrokeWidth(paramInt3);
            localCanvas.drawCircle(paramInt1 / 2, paramInt2 / 2, i - paramInt3, paint);
        }
        return localBitmap;
    }
}